﻿using System;
using Gol.Domain;

namespace Gol.UI.Winforms
{
    public class FormPresenter
    {
        private readonly IFormView _view;
      
        private GameOfLife _gameOfLife;
     
        private int _rows;
        private int _cols;
     

        public FormPresenter(IFormView view)
        {
            _view = view;
        }

        public void Initialize()
        {
            var size = _view.GetBoardSize();
            _rows = size[0,0];
            _cols = size[0,1];
            _gameOfLife = new GameOfLife(_rows, _cols);

            _view.SetupGrid();

            int[,] lifeOnes = GetLifeOnes(1000);

            _gameOfLife.Start(lifeOnes);

            _view.ShowGridContent(_gameOfLife.CellGrid);
        }

        public void Step()
        {
            _view.StopTimer();

            this._gameOfLife.NextGeneration();

            _view.ShowGridContent(this._gameOfLife.CellGrid);
        }

        

        private int[,] GetLifeOnes(int max)
        {
            var lifeOnes = new int[max, 2];
            Random r = new Random();

            for (int i = 0; i < max; i++)
            {
                lifeOnes[i, 0] = r.Next(this._rows);
                lifeOnes[i, 1] = r.Next(this._cols);
            }
            return lifeOnes;
        }


        internal void Animate()
        {
            _view.StartTimer();
        }

        internal void Randomize()
        {
            _view.StopTimer();

            int[,] lifeOnes = GetLifeOnes(1000);

            _gameOfLife.Start(lifeOnes);

            _view.ShowGridContent(this._gameOfLife.CellGrid);
        }

        internal void NextState()
        {
            this._gameOfLife.NextGeneration();

            _view.ShowGridContent(this._gameOfLife.CellGrid);
        }
    }
}